\71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period .
refers to the current directory. Furthermore, a double period ..
moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /
, and there must be only a single slash /
between two directory names. The last directory name (if it exists) must not end with a trailing /
. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
1 | Input: "/home/" |
Example 2:
1 | Input: "/../" |
Example 3:
1 | Input: "/home//foo/" |
Example 4:
1 | Input: "/a/./b/../../c/" |
Example 5:
1 | Input: "/a/../../b/../c//.//" |
Example 6:
1 | Input: "/a//b////c/d//././/.." |
乍眼一看可能觉得无从下手,甚至不知道怎么做。但是冷静下来就能发现规律。首先我们发现文件路径都是使用‘/’进行划分的,所以对于输入可以使用route = path.split('/')
进行处理,同时也能处理掉多余的‘/’。然后我们发现出现“.”的时候,停留在当前路径;出现“..”的时候,回到上一层;出现“dirName”的时候,进入相应的dir。我们从中隐隐约约感觉到可以使用stack进行处理。对应关系如下:
出现“.”的时候,停留在当前路径:stack不变
出现“..”的时候,回到上一层:stack.pop()
出现“dirName”的时候,进入相应的dir:stack.append(dirName)
思路就出来了,然后需要注意一下edge case。比如stack为空的时候我们并不是什么都不输出,而是需要输出 ‘/’
1 | class Solution: |
简化版,在处理输入时就排除空和’.’的情况
1 | class Solution: |